<!--
Date: 2025-08-13
Copyright (c) 2025 CAX Conversion Project
-->
<template>
  <div class="elements_main" v-loading="loading" element-loading-text="加载中...">
    <div class="left">
      <div class="top_btn">
        <el-button size="small" type="primary" icon="Download" @click="downloadElements">导出模型状态清单</el-button>
      </div>
      <div class="tree">
        <el-input size="small" class="input" v-model="filterText" placeholder="请输入">
          <template #append> <el-button size="small" icon="Search" /> </template
        ></el-input>
        <el-tree
          ref="treeRef"
          :data="treeData"
          class="filter-tree"
          node-key="id"
          highlight-current
          :props="defaultProps"
          default-expand-all
          :default-checked-keys="checkedKey"
          :expand-on-click-node="false"
          :current-node-key="0"
          icon-class="el-icon-arrow-right"
          @node-click="treeSelect"
          :filter-node-method="filterNode"
        >
          <template #default="{ node, data }">
            <span class="custom-tree-node">
              <span class="node-title" v-if="node.level === 2">{{ node.label }}({{ data.mark }}) </span>
              <span class="node-title" v-else>{{ node.label }} </span>
            </span>
          </template>
        </el-tree>
      </div>
    </div>
    <div class="right">
      <el-form inline size="small" label-width="80" class="form_class">
        <el-form-item label="零件号:">
          <el-input class="form_input" placeholder="请输入" v-model="queryParams.partNumber" />
        </el-form-item>
        <el-form-item label="零件名称:">
          <el-input class="form_input" placeholder="请输入" v-model="queryParams.name" />
        </el-form-item>
        <el-form-item label="版本号:">
          <el-input class="form_input" placeholder="请输入" v-model="queryParams.versionNumber" />
        </el-form-item>
        <el-form-item style="padding-left: 80px">
          <el-button type="primary" size="small" @click="queryByCondition('like')"> 查询 </el-button>
          <el-button style="margin-left: 10px" @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
      <div>
        <el-dropdown trigger="click">
          <el-button type="primary" size="small" icon="UploadFilled"
            >导入<el-icon class="el-icon--right"><arrow-down /></el-icon
          ></el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="partImport">零件导入</el-dropdown-item>
              <el-dropdown-item @click="buttonClick('import')">整机导入</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>

        <el-button type="primary" size="small" icon="Download" style="margin-left: 10px">下载</el-button>
      </div>
      <div class="table_div">
        <el-table :data="tableData" style="width: 100%; height: calc(100vh - 255px)" @selection-change="handleSelectionChange">
          <el-table-column type="selection" />
          <el-table-column type="expand">
            <template #default="scope">
              <div style="padding-left: 48px">
                <el-table :data="scope.row.versionVoList" @selection-change="handleSubSelectionChange">
                  <el-table-column type="selection" />
                  <el-table-column label="版本号" prop="versionNumber"></el-table-column>
                  <el-table-column label="数量" prop="amount"></el-table-column>
                  <el-table-column label="单件重量(KG)" prop="unitWeight"></el-table-column>
                  <el-table-column label="材料" prop="material"></el-table-column>
                  <el-table-column label="操作">
                    <template #default="scope">
                      <el-button size="small" link type="primary" icon="EditPen" @click="buttonClick('view', scope.row)">查看</el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="零件号" prop="partNumber"></el-table-column>
          <el-table-column label="名称" prop="name"></el-table-column>
        </el-table>
        <div class="pagenation">
          <el-pagination
            v-show="total > 0"
            layout="prev, pager, next,jumper"
            v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize"
            :total="total"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>
    <ElementView :data="viewData" v-if="elementVisible" :elementVisible="elementVisible" @close="close" />
    <ImportPart v-if="visible" :visible="visible" @handleEvent="handleEvent" />
  </div>
</template>
<script setup name="Models">
import ElementView from './ElementView.vue';
import ImportPart from './ImportPart.vue';
import { getModelListTree, getModelList, exportPartsBom } from '@/api/elementsLibrary';
import { downloadFile } from '../../util/util';

const emit = defineEmits(['handleEvent']);
const defaultProps = { children: 'children', label: 'label' };
const treeData = ref([]);
const checkedKey = ref([]);
const treeRef = ref();
const elementVisible = ref(false);
const filterText = ref('');
const tableData = ref([]);
const queryParams = ref({ pageNum: 1, pageSize: 10 });
const treeNode = ref(null);
const total = ref(0);
const viewData = ref(null);
const loading = ref(false);
const visible = ref(false);
// 树点击事件
const treeSelect = (selected, node) => {
  treeNode.value = node;
  //清空树查询信息
  queryParams.value.modelNumber = '';
  queryParams.value.sectionNumber = '';
  queryParams.value.componentNumber = '';
  //执行查询
  if (node.level === 1) {
    queryParams.value.modelNumber = node.data.mark;
  }
  if (node.level === 2) {
    const parentId = node.parent.data.mark;
    queryParams.value.modelNumber = parentId;
    queryParams.value.sectionNumber = node.data.mark;
  }
  if (node.level === 3) {
    const parentId = node.parent.data.mark;
    const parentId2 = node.parent.parent.data.mark;
    queryParams.value.modelNumber = parentId2;
    queryParams.value.sectionNumber = parentId;
    queryParams.value.componentNumber = node.data.mark;
  }
  queryByCondition();
};
const partImport = () => {
  visible.value = true;
};
const handleEvent = (data) => {
  if (data?.type === 'refresh') {
    queryByCondition();
  }
  visible.value = false;
};
const buttonClick = (type, data) => {
  if (type === 'view') {
    elementVisible.value = true;
    viewData.value = data;
  }
  if (type === 'import') {
    emit('handleEvent', { component: 'Elements', type: 'import' });
  }
};
// 重置
const reset = () => {
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    partNumber: '',
    name: '',
    versionNumber: ''
  };
  queryByCondition();
};
const handleCurrentChange = (num) => {
  queryParams.value.pageNum = num;
  queryByCondition();
};
const close = () => {
  elementVisible.value = false;
};
watch(filterText, (val) => {
  treeRef.value.filter(val);
});
const filterNode = (value, data) => {
  if (!value) return true;
  return data.label.includes(value);
};
// 主表checkbox选择事件
const handleSelectionChange = () => {};
// 子表checkbox选择事件
const handleSubSelectionChange = () => {};

const processData = (data) => {
  const labelData = data.map((el) => {
    if (el.children) {
      el = { ...el, label: el.name };
      el.children = processData(el.children);
    } else {
      el = { ...el, label: el.name };
    }
    return el;
  });
  return labelData;
};
// 查询左侧树结构
const doqueryTree = () => {
  getModelListTree()
    .then(async (res) => {
      if (res) {
        const dataArr = res?.data || [];
        const returnData = await processData(dataArr);
        treeData.value = returnData;
      }
    })
    .finally(() => {
      loading.value = false;
    });
};
// 查询模型列表
const queryByCondition = (type) => {
  type === 'eq' ? (queryParams.value.queryMode = 'eq') : (queryParams.value.queryMode = 'like');
  getModelList(queryParams.value).then((res) => {
    if (res) {
      tableData.value = res?.rows;
      total.value = res?.total;
    }
  });
};
// 导出零组件模型清单
const downloadElements = () => {
  if (!queryParams.value.modelNumber) {
    ElMessage({ showClose: true, message: '请选择机型再进行数据导出！', type: 'error' });
    return;
  }
  exportPartsBom({ modelNumber: queryParams.value.modelNumber }).then((res) => {
    if (res?.code === 500) {
      ElMessage({ showClose: true, message: '下载失败。', type: 'error' });
      return;
    }
    downloadFile(res, `模型状态清单-${queryParams.value.modelNumber}`, 'xlsx');
  });
};
onMounted(() => {
  loading.value = true;
  doqueryTree();
  queryByCondition();
});
</script>
<style lang="scss" scoped>
.elements_main {
  height: calc(100vh - 84px);
  display: flex;
  .left {
    width: 200px;
    padding: 10px;
    height: calc(100vh - 84px);
    overflow: auto;
    border-right: 1px solid #dddddd7a;
    display: flex;
    flex-direction: column;
    align-items: left;
    .tree {
      .input {
        margin-top: 5px;
      }
      .custom-tree-node {
        font-size: 12px;
      }
    }
  }
  .right {
    flex: 1;
    overflow: auto;
    padding-top: 10px;
    margin-left: 20px;
    margin-right: 20px;
    height: calc(100vh - 84px);
    .form_class {
      border: 1px solid #dddddd7a;
      padding: 10px;
      margin-top: 10px;
      margin-bottom: 10px;
      .form_input {
        width: 180px;
      }
    }
    .table_div {
      margin-top: 10px;
      .pagenation {
        display: flex;
        justify-content: end;
        margin-top: 10px;
        margin-right: 10px;
        margin-bottom: 10px;
      }
    }
  }
  :deep(.el-tree-node__label) {
    font-size: 12px;
  }
}
</style>